<template>
  <div class="p-2">
    <el-row :gutter="20">
      <!--      &lt;!&ndash; 区域树 &ndash;&gt;-->
      <!--      <el-col :lg="4" :xs="24" style="">-->
      <!--        <el-card shadow="hover">-->
      <!--          <el-input v-model="deptName" placeholder="请输入区域名称" prefix-icon="Search" clearable />-->
      <!--          <el-tree-->
      <!--            ref="deptTreeRef"-->
      <!--            class="mt-2"-->
      <!--            node-key="id"-->
      <!--            :data="deptOptions"-->
      <!--            :props="{ label: 'label', children: 'children' }"-->
      <!--            :expand-on-click-node="false"-->
      <!--            :filter-node-method="filterNode"-->
      <!--            highlight-current-->
      <!--            default-expand-all-->
      <!--            @node-click="handleNodeClick"-->
      <!--          />-->
      <!--        </el-card>-->
      <!--      </el-col>-->
      <el-col>
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                    :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div v-show="showSearch" class="mb-[10px]">
            <el-card shadow="hover">
              <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <el-form-item label="保险公司编码" prop="postCode">
                  <el-input v-model="queryParams.postCode" placeholder="请输入保险公司编码" clearable
                            @keyup.enter="handleQuery" />
                </el-form-item>
                <!--                <el-form-item label="类别编码" prop="postCategory">-->
                <!--                  <el-input-->
                <!--                    v-model="queryParams.postCategory"-->
                <!--                    placeholder="请输入类别编码"-->
                <!--                    clearable-->
                <!--                    style="width: 200px"-->
                <!--                    @keyup.enter="handleQuery"-->
                <!--                  />-->
                <!--                </el-form-item>-->
                <el-form-item label="保险公司名称" prop="postName">
                  <el-input v-model="queryParams.postName" placeholder="请输入保险公司名称" clearable
                            @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="区域" prop="deptId">
                  <el-tree-select
                    v-model="queryParams.deptId"
                    :data="deptOptions"
                    :props="{ value: 'id', label: 'label', children: 'children' }"
                    value-key="id"
                    placeholder="请选择区域"
                    check-strictly
                  />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                  <el-select v-model="queryParams.status" placeholder="保险公司状态" clearable>
                    <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label"
                               :value="dict.value" />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </transition>
        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:post:add']" type="primary" plain icon="Plus" @click="handleAdd">新增
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:post:edit']" type="success" plain icon="Edit" :disabled="single"
                           @click="handleUpdate()"
                >修改
                </el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:post:remove']" type="danger" plain icon="Delete" :disabled="multiple"
                           @click="handleDelete()">
                  删除
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:post:export']" type="warning" plain icon="Download"
                           @click="handleExport">导出
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain icon="Upload" @click="handleImport"
                           v-hasPermi="['system:post:export']"
                >导入
                </el-button
                >
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
            </el-row>
          </template>
          <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" align="center" width="60">
              <template #default="scope">
                {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column min-width="90" max-width="100" label="保险公司编码" align="center" prop="postCode" />
            <!--            <el-table-column label="类别编码" align="center" prop="postCategory" />-->
            <el-table-column min-width="300" max-width="330" label="保险公司名称" align="center" prop="postName" />
            <el-table-column label="区域" align="center" prop="deptName" />
            <el-table-column label="排序" align="center" prop="postSort" />
            <el-table-column label="状态" align="center" prop="status">

            </el-table-column>
            <el-table-column label="客服电话" min-width="110" max-width="150" align="center" prop="customerNumber" />
            <!--            <el-table-column label="创建时间" align="center" prop="createTime" width="180">-->
            <!--              <template #default="scope">-->
            <!--                <span>{{ parseTime(scope.row.createTime) }}</span>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
              <template #default="scope">


                <!-- 详情按钮 -->
                <el-tooltip content="详情" placement="top">
                  <el-button link type="primary" icon="View" @click="handleView(scope.row)"
                             v-hasPermi="['system:post:edit']"></el-button>
                </el-tooltip>

                <el-tooltip content="修改" placement="top">
                  <el-button v-hasPermi="['system:post:edit']" link type="primary" icon="Edit"
                             @click="handleUpdate(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button v-hasPermi="['system:post:remove']" link type="primary" icon="Delete"
                             @click="handleDelete(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :total="total"
            @pagination="getList"
          />
        </el-card>

        <!--数据导入对话框 -->
        <el-dialog title="数据导入" v-model="excelOpen" width="400px" append-to-body>
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            :auto-upload="false"
            :on-change="handleChange"
            :limit="1"
            accept=".xlsx,.xls">
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <el-button class="ml-3" type="success" @click="submitUpload">上传</el-button>
            <template #tip>
              <el-button class="ml-3" type="success" @click="handleExportTemplate">下载导入模版</el-button>
              <div class="el-upload__tip">上传文件仅支持，xls/xlsx格式，文件大小不得超过20M</div>
            </template>
          </el-upload>
        </el-dialog>

        <!-- 添加或修改保险公司对话框 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
          <el-form ref="postFormRef" :model="form" :rules="rules" label-width="110px">
            <el-form-item label="保险公司名称" prop="postName">
              <el-input v-model="form.postName" placeholder="请输入保险公司名称" />
            </el-form-item>
            <el-form-item label="区域" prop="deptId">
              <el-tree-select
                v-model="form.deptId"
                :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="id"
                placeholder="请选择区域"
                check-strictly
              />
            </el-form-item>
            <el-form-item label="保险公司编码" prop="postCode">
              <el-input v-model="form.postCode" placeholder="请输入编码名称" />
            </el-form-item>
            <el-form-item label="客服电话" prop="customerNumber">
              <el-input v-model="form.customerNumber" placeholder="请输入客服电话" />
            </el-form-item>
            <!--            <el-form-item label="类别编码" prop="postCategory">-->
            <!--              <el-input v-model="form.postCategory" placeholder="请输入
            编码" />-->
            <!--            </el-form-item>-->
            <el-form-item label="保险公司顺序" prop="postSort">
              <el-input-number v-model="form.postSort" controls-position="right" :min="0" />
            </el-form-item>
            <el-form-item label="保险公司状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="保险公司简介" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </el-dialog>

        <!-- 详情对话框 -->
        <el-dialog :title="dialog2.title" v-model="dialog2.visible" width="800px" append-to-body>
          <el-form ref="postFormRef" :model="form2" :rules="rules" label-width="110px">
            <el-card class="mb-4">
              <template #header>
                <div class="card-header">
                  <span class="title">保险公司基本信息</span>
                </div>
              </template>
              <el-descriptions :column="2" border>

                  <el-descriptions-item label="保险公司名称" prop="postName">
                    {{ form2.postName }}
                  </el-descriptions-item>

                  <el-descriptions-item label="区域" prop="deptName">
                    {{ form2.deptName }}
                  </el-descriptions-item>

                  <el-descriptions-item label="保险公司编码" prop="postCode">
                    {{ form2.postCode }}
                  </el-descriptions-item>

                  <el-descriptions-item label="客服电话" prop="customerNumber">
                    {{ form2.customerNumber }}
                  </el-descriptions-item>

                  <el-descriptions-item label="保险公司顺序" prop="postSort">
                    {{ form2.postSort }}
                  </el-descriptions-item>

                  <el-descriptions-item label="保险公司状态" prop="status">
                    {{ form2.status }}
                  </el-descriptions-item>

                  <el-descriptions-item label="保险公司简介" prop="remark">
                    {{ form2.remark }}
                  </el-descriptions-item>
              </el-descriptions>
            </el-card>
            <el-card class="mb-4">
              <template #header>
                <div class="card-header">
                  <span class="title">其它信息</span>
                </div>
              </template>
              <el-descriptions :column="2" border>

                <el-descriptions-item label="公司级别" prop="companyLevel">
                  {{ form2.companyLevel }}
                </el-descriptions-item>
                <el-descriptions-item label="省" prop="province">
                  {{ form2.province }}
                </el-descriptions-item>
                <el-descriptions-item label="市" prop="city">
                  {{ form2.city }}
                </el-descriptions-item>
                <el-descriptions-item label="区县" prop="district">
                  {{ form2.district }}
                </el-descriptions-item>
                <el-descriptions-item label="机构负责人" prop="agencyHead">
                  {{ form2.agencyHead }}
                </el-descriptions-item>
                <el-descriptions-item label="邮箱" prop="email">
                  {{ form2.email }}
                </el-descriptions-item>
                <el-descriptions-item label="申请日期" prop="applicationDate">
                  {{ form2.applicationDate }}
                </el-descriptions-item>
                <el-descriptions-item label="入驻日期" prop="occupancyDate">
                  {{ form2.occupancyDate }}
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="cancel">返 回</el-button>
            </div>
          </template>
        </el-dialog>


      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Post" lang="ts">
import { listPost, addPost, delPost, getPost, updatePost, exportSelected } from '@/api/system/post';
import { Post, PostForm, PostQuery, PostVO } from '@/api/system/post/types';
import { DeptVO } from '@/api/system/dept/types';
import api from '@/api/system/user';
import { importExcel } from '@/api/system/post';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

const postList = ref<PostVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const deptName = ref('');
const deptOptions = ref<DeptVO[]>([]);
const deptTreeRef = ref<ElTreeInstance>();
const postFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();


const selectedRows = ref<PostVO[]>([]);

const exportSelectedRows = async (rows: PostVO[]) => {
  try {
    const ids = rows.map(row => row.postId);
    console.log('正在导出的ID:', ids); // 添加中文日志
    const response = await exportSelected(ids);
    console.log('导出响应:', response); // 添加中文日志
    const url = window.URL.createObjectURL(new Blob([response]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `post_${new Date().getTime()}.xlsx`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } catch (error) {
    console.error('导出选中的数据失败:', error);
    proxy?.$modal.msgError('导出选中的数据失败');
  }
};

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const dialog2 = reactive<DialogOption>({
  visible: false,
  title: ''
});


const initFormData2: Post = {
  companyLevel: undefined,
  province: undefined,
  city: undefined,
  district: undefined,
  agencyHead: undefined,
  email: undefined,
  applicationDate: undefined,
  occupancyDate: undefined,
  postId: undefined,
  deptId: undefined,
  postCode: '',
  postName: '',
  postCategory: '',
  deptName: '',
  customerNumber: '',
  postSort: 0,
  status: '0',
  remark: ''
};

const data2 = reactive<PageData<Post, PostQuery>>({
  form: { ...initFormData2 },

});

const initFormData: PostForm = {
  postId: undefined,
  deptId: undefined,
  postCode: '',
  postName: '',
  postCategory: '',
  postSort: 0,
  status: '0',
  remark: ''
};

const data = reactive<PageData<PostForm, PostQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    postCode: '',
    postName: '',
    postCategory: '',
    status: ''
  },
  rules: {
    postName: [{ required: true, message: '保险公司名称不能为空', trigger: 'blur' }],
    postCode: [{ required: true, message: '保险公司编码不能为空', trigger: 'blur' }],
    deptId: [{ required: true, message: '区域不能为空', trigger: 'blur' }],
    postSort: [{ required: true, message: '保险公司顺序不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs<PageData<PostForm, PostQuery>>(data);
const { form: form2 } = toRefs<PageData<Post, PostQuery>>(data2);


/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

/** 根据名称筛选区域树 */
watchEffect(
  () => {
    deptTreeRef.value?.filter(deptName.value);
  },
  {
    flush: 'post' // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);

/** 查询区域下拉树结构 */
const getTreeSelect = async () => {
  const res = await api.deptTreeSelect();
  deptOptions.value = res.data;
};

/** 节点单击事件 */
const handleNodeClick = (data: DeptVO) => {
  queryParams.value.belongDeptId = data.id;
  queryParams.value.deptId = undefined;
  handleQuery();
};

// /** 查询保险公司列表 */
// const getList = async () => {
//   loading.value = true;
//   const res = await listPost(queryParams.value);
//   postList.value = res.rows;
//   total.value = res.total;
//   loading.value = false;
// };


const getList = async () => {
  loading.value = true;
  const res = await listPost(queryParams.value);
  postList.value = res.rows;
  total.value = res.total;
  loading.value = false;
  console.log('加载的岗位列表:', postList.value); // 添加日志
};


/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  dialog2.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  postFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  if (queryParams.value.deptId) {
    queryParams.value.belongDeptId = undefined;
  }
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  queryParams.value.deptId = undefined;
  deptTreeRef.value?.setCurrentKey(undefined);
  /** 清空左边区域树选中值 */
  queryParams.value.belongDeptId = undefined;
  handleQuery();
};

// /** 多选框选中数据 */
// const handleSelectionChange = (selection: PostVO[]) => {
//   ids.value = selection.map((item) => item.postId);
//   single.value = selection.length != 1;
//   multiple.value = !selection.length;
// };


const handleSelectionChange = (selection: PostVO[]) => {
  ids.value = selection.map(item => item.postId);
  selectedRows.value = selection; // 存储选中的数据行
  single.value = selection.length !== 1;
  multiple.value = selection.length === 0;
  console.log('选中的数据:', selectedRows.value); // 添加日志
};


/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加保险公司';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: PostVO) => {
  reset();
  const postId = row?.postId || ids.value[0];
  const res = await getPost(postId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改保险公司';
};

/** 提交按钮 */
const submitForm = () => {
  postFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.postId ? await updatePost(form.value) : await addPost(form.value);
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: PostVO) => {
  const postIds = row?.postId || ids.value;
  await proxy?.$modal.confirm('是否确认删除保险公司编号为"' + postIds + '"的数据项？');
  await delPost(postIds);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

// /** 导出按钮操作 */
// const handleExport = () => {
//   proxy?.download(
//     'system/post/export',
//     {
//       ...queryParams.value
//     },
//     `post_${new Date().getTime()}.xlsx`
//   );
// };

const handleExport = () => {
  if (selectedRows.value.length > 0) {
    exportSelectedRows(selectedRows.value);
  } else {
    proxy?.download('system/post/export', {
      ...queryParams.value
    }, `post_${new Date().getTime()}.xlsx`);
  }
};


// 详情按钮操作
const handleView = async (row?: PostVO) => {
  reset();
  const postId = row?.postId || ids.value[0];
  const res = await getPost(postId);
  Object.assign(form2.value, res.data);
  dialog2.visible = true;
  dialog2.title = '保险公司详情';
};


/* 打开数据导入的对话框 */
const excelOpen = ref(false);


function handleImport() {
  excelOpen.value = true;
}


// 存储选择的文件
const selectedFile = ref(null);


// 文件选择变化时的处理
const handleChange = (file) => {
  selectedFile.value = file.raw;
};


// 提交上传
const submitUpload = async () => {
  if (!selectedFile.value) {
    proxy?.$modal.msgError('请先选择文件');
    return;
  }

  try {
    proxy?.$modal.loading('正在上传excel，请稍候...');
    const res = await importExcel(selectedFile.value);
    if (res.code === 200) {
      proxy?.$modal.msgSuccess('上传excel成功');
      excelOpen.value = false;
      getList();
    } else {
      proxy?.$modal.msgError(res.msg);
    }
  } catch (error) {
    proxy?.$modal.msgError('上传excel失败');
  } finally {
    proxy.$modal.closeLoading();
    uploadRef.value.clearFiles();
  }

};


/** 下载导入模版 */
const handleExportTemplate = () => {
  proxy?.download(
    'system/post/template',
    {},
    `保险公司信息导入模版.xlsx`
  );
};

onMounted(() => {
  getTreeSelect(); // 初始化区域数据
  getList();
});
</script>
